﻿using Castle.Core.Internal;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using VOL.Core.DBManager;
using VOL.WebApi.Controllers.Finance.Partial;

namespace VOL.WebApi.Controllers.MyTable.Partial
{
    [Route("api/fwb_turnable_lottery")]
    [ApiController]
    public class fwb_turnable_lottery: Controller
    {
        [HttpPost,Route("getAwardInfo"),AllowAnonymous]
        public List<string> GetAwardInfo(string goodId)
        {
            List<dynamic> result = new List<dynamic>();
            List<dynamic> result1 = new List<dynamic>();
            List<string> list = new List<string>();
            Random random = new Random();
            int randomIndex = 0;
            Thread.Sleep(random.Next(400, 1000));     

            try
            {
                string sql = "select componentnum,prize_number,probablility_winning from fwb_prize_list fpl order by componentnum";
                result = DBServerProvider.SqlDapper.QueryList<dynamic>(sql, null).ToList();
                double allPresent = 0;
                int index = 0;
                double zeroPresent = 0;
                double averagePresent = 0;
                for(int i = result.Count - 1; i >= 0; i--)
                {
                    string componentnum = result[i].componentnum;
                    if (result[i].prize_number == "0" && !componentnum.IsNullOrEmpty())
                    {
                        double probablility = double.Parse(result[i].probablility_winning.TrimEnd('%')) / 100;
                        zeroPresent += probablility;
                        result.RemoveAt(i);
                    }
                }
                averagePresent = zeroPresent / result.Count;
                //各奖品概率区段
                double[] present = new double[result.Count];
                result.ForEach(x =>
                {
                    double probablility = double.Parse(x.probablility_winning.TrimEnd('%')) / 100;
                    present[index++] = allPresent + probablility + averagePresent;
                    allPresent += probablility+averagePresent;
                });
                double awardRandom = random.NextDouble();
                for (int i=0;i<present.Length;i++)
                {
                    if (awardRandom < present[i])
                    {
                        randomIndex = i;
                        break;
                    }
                }
                //奖品列表排序后，第一位为谢谢参与
                if (randomIndex != 0)
                {
                    updatePrizeList(result, randomIndex);
                }

                string querySql = null;
                if (randomIndex != 0)
                {
                    querySql = "select fwb_prize_list_id,prize_name,componentnum,image_url from fwb_prize_list fpl where componentnum = '" + result[randomIndex].componentnum + "'";
                }
                else
                {
                    querySql = "select fwb_prize_list_id,prize_name,componentnum,image_url from fwb_prize_list fpl where componentnum is null";
                }
                result1 = DBServerProvider.SqlDapper.QueryList<dynamic>(querySql, null).ToList();
                list.Add(result1.First().fwb_prize_list_id.ToString());
                list.Add(result1.First().prize_name);
                list.Add(result1.First().componentnum);
                list.Add(result1.First().image_url);
                list.Add(getDrawInfoId(goodId, result1.First().fwb_prize_list_id.ToString()));
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }
            return list;
        }

        //抽中奖品，更新数据
        private void updatePrizeList(List<dynamic> prizeList,int awardIndex)
        {
            double[] probablilitys=new double[prizeList.Count];
            for(int index=0;index<prizeList.Count;index++)
            {
                probablilitys[index] = double.Parse(prizeList[index].probablility_winning.TrimEnd('%')) / 100;
            }
            double awardProbablility = probablilitys[awardIndex];

            //抽中奖品后，更新奖品数量
            string sql = "update fwb_prize_list set prize_number = prize_number - 1 where componentnum ='" + prizeList[awardIndex].componentnum +"'";
            DBServerProvider.SqlDapper.ExcuteNonQuery(sql, null);

            ////奖品数量变为0时，中奖概率变为0，上调其他奖品概率
            //if (prizeList[awardIndex].prize_number == "1")
            //{
            //    double averageProbablility = awardProbablility / (prizeList.Count - 2);
            //    for(int index=1; index < prizeList.Count; index++)
            //    {
            //        string sql1 = null;
            //        if (index != awardIndex)
            //        {
            //            double newPro = probablilitys[index] + averageProbablility;
            //            string newProbablility = String.Format("{0:F}", (newPro * 100)) + "%";
            //            sql1 = "update fwb_prize_list set probablility_winning = '" + newProbablility + "' where componentnum = '" + prizeList[index].componentnum + "'";
            //            DBServerProvider.SqlDapper.ExcuteNonQuery(sql1, null);
            //        }
            //        else
            //        {
            //            sql1 = "update fwb_prize_list set probablility_winning = '0%' where componentnum = '" + prizeList[index].componentnum + "'";
            //            DBServerProvider.SqlDapper.ExcuteNonQuery(sql1, null);
            //        }
            //    }
            //}
        }

        //更新抽奖信息表，返回信息表id
        private string getDrawInfoId(string goodId, string awardId)
        {
            string drawInfoId=Guid.NewGuid().ToString();
            string CreateDate = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff");
            string sql = "insert into fwb_prize_draw_info (fwb_prize_draw_info_id,fwb_prize_list_id,fwb_onLine_good_reputation_id,CreateDate) values(@drawInfoId,@awardId,@goodId,@CreateDate)";
            DBServerProvider.SqlDapper.ExcuteNonQuery(sql, new { drawInfoId, awardId, goodId, CreateDate });
            return drawInfoId;
        }
    }
}
